<template>
    <div style="padding:0px 5px">
        <header class="title">
          <div><span style="font:1.6rem/2rem '宋体';vertical-align:-15px">购物车</span>  </div>
            <div class="title-aside">
                <img src="../assets/free.png"/>
                <span v-if="isEdit == false" style="font:1.3rem/2rem '宋体'; margin-left:4px" @click="changeEdit('edit')"> 编辑</span>
                <span v-else  style="font:1.3rem/2rem '宋体'; margin-left:4px" @click="changeEdit('finish')">完成</span>
                </div>
        </header>
        <article class="goods-list">
          
          <section class="free" v-if="shoppingCartList==null||shoppingCartList.length==0">
                <img class="free-img" src="../assets/shoppingCart_free.png"/>
                <div>购物车还是空的</div>
                <div class="button">  随便看看</div>
          </section>
          <section class="full" v-else>
           <div v-for="goods of shoppingCartList" :key="goods.id">
               <div class="goods-item">
                   <div>
                        <input type="checkbox" class="normal-checkbox" v-model="goods.selected" @change="changeState()">
                        </div>
                    <div>   
                        <img class="item-img" :src="goods.imageURL"/>
                     </div>
        
                     <!-- 商品信息-->
                    <div class="item-detail" padding-right:20px>
                        <div><span style="font: 1.1rem/2rem '宋体';vertical-algin:top">{{goods.name}}</span></div>
                        <div v-if="isEdit == false">
                          <span style="color:#888;font-size:1.1rem/2rem" v-for="(item,index) in goods.model" :key="index">
                            {{item.value}}
                          </span>
                          </div>
                       <!--处于编辑状态时 修改商品的型号-->
                        <div v-else >
                            
                              <div  @click="showActionSheet(goods)" style="color:#888;font-size:1.1rem/2rem;margin-right:10px;background-color:#f0f0f0;border:1px solid #e0e0e0">
                              
                                    <span style="color:#888;font-size:1.1rem/2rem" v-for="(item,index) in goods.model" :key="index">
                                           {{item.value}}
                                        </span>                     
                              </div>
                             <aside>
                               <van-action-sheet title="商品参数修改" cancel-text="确定" v-model="isShowActionSheet" >
                                 <div class="model-content">
                                  <header>
                                    <div style="margin:20px 20px 10px 20px;border:1px solid #E0E0E0;border-radius:5px;">
                                      <img v-bind:src="actionSheetGoods.imageURL">
                                    </div>
                                    <div>
                                      <div style="text-align:left;color:#ff6700;margin-top:15px;">
                                        <span style="font-size:1.2rem;line-height:50px;vertical-align:top">￥</span>
                                        <span style="font:bold 2rem/50px '宋体'">{{actionSheetGoods.price}}</span>
                                      </div>
                                      <div style="font:bold 1rem/2rem '宋体'">{{actionSheetGoods.name}}
                                      <span v-for="(item,index) in actionSheetGoods.model" :key="index">
                                        {{item.value}}
                                        </span>
                                      </div>
                                    </div>
                                  </header>
                                  <div style='background-color:#e0e0e0;height:1px;border:none;'></div>
                                 <article>
                                     <section>
                                       <!-- 外层循环 循环型号的名称-->
                                       <div v-for="(model,index) in newProductModel" :key="index" style="margin:20px">
                                       <span style="font-size:16px;">  {{model.modelName}}</span>
                                      <!-- 内层循环 循环各个型号值-->
                                       <div style="display: flex;flex-direction: row; font:1.3rem/2rem '宋体'; color:#999;margin-top:20px" >
                                            <div v-for="(myvalue,index) in model.values" :key="index" style="margin-left:20px" @click="changeModelValue(actionSheetGoods,model.modelName,myvalue.name)" >
                                              <span :class="{valueselected:myvalue.state }">{{myvalue.name}}</span>

                                              </div>
                                         </div>
                                       </div>
                                       <!--数量的显示-->
                                       <div style="margin:20px">
                                         <div style="font-size:16px;"> 数量</div>
                                         <div style="display: flex;flex-direction: row; font:1.3rem/2rem '宋体'; color:#999;float:right" >
                                            <button class="normal-button"  v-on:click="reduce(actionSheetGoods)">-</button>
                                            <input type="number" class= "normal-input" v-model="actionSheetGoods.number"/>
                                            <button class="normal-button" v-on:click="add(actionSheetGoods)" >+</button>

                                            </div>
                                         </div>
                                     </section>
                                                             
                                 </article>
                                </div>
                               </van-action-sheet>
                               </aside>
                             
                          </div>
                        <div>￥<span style="font-size:1.4rem/2rem;color:#ff6600">{{goods.price}}</span></div>
                        </div>
                    <!-- 商品数量-->
                    <div class="item-button">
                    <button class="normal-button" v-on:click="reduce(goods)">-</button>
                    <input type="number" class= "normal-input" v-model="goods.number"/>
                    <button class="normal-button" v-on:click="add(goods)" >+</button>
                    </div> 
             </div>
            </div>

            </section>
         </article>
        <aside class="recommend-list">
            <header class="title">
                  <img src="../assets/recommend.jpg" />
                  <div style="font-size:1.2rem;color:#707070">买了以上产品的人还买了</div>
            </header>
            <!--推荐的商品列表-->
            <nav class="recommend-goods-list" >
              <div class ="recommend-item" v-for="goods of recommendGoodsList" :key="goods.id">
                   <img :src="goods.imageURL" class="goods-item-img">
                   <!--展示商品的基本信息-->
                   <div >
                       <div  style="font-size:1.2rem;">
                         <span> {{goods.name}} </span>
                       
                       <!-- 展示商品的型号-->
                              <span v-for="(model,index) in goods.model" :key="index">
                                {{model.value}}
                                </span>
                          <div style=" width:22px;height:22px;border:1px solid #ccc; border-radius:8px;float:right" @click="addShoppingCart(goods)"><img style="width:20px;height:20px" src="../assets/shoppingCart_free.png"/></div>      
                        </div>
                        <div style="color:#999" >{{goods.discription}}
                          <div style="color:#ff6600"> <sup>￥</sup><span style="font-size:1.5rem"> {{goods.price}}</span></div>
                         </div>
                       
                     </div>
             </div>
              </nav>

        </aside>
        <footer class="settlement">
          <div>
            <input type="checkbox" class="normal-checkbox" v-model="allSelected"  @change="changeAllSelect()"/>
            <span style="font: 1.3rem/2rem '宋体';vertical-algin:top;padding-left:0px"  > 全选</span>
            </div>
            <div v-if="isEdit == false"  class="no-edit">
            <div>
             <span style="margin-left:50px;font:1.3rem/2rem '宋体';">
                    合计:
                    <span style="color:#ff6600;font-size:1.3rem"  >￥{{totalPrice}}</span>
               </span>

           </div>
            <div  v-bind:class="{gray:totalProductsNum==0}" class="button"  ><span style="text-align:center;font:bold 1.5rem/5rem '宋体';color:#fff; vertical-algin:top">结算</span>（{{totalProductsNum}}）</div>
           </div>
           <div v-else class="no-edit" >
                <header style="background-color:#FF6700;width:150px;flex-grow:1">
          <span style="font:600 1.2rem/50px '宋体';color:white">移入收藏</span>
        </header>
        <footer style="background-color:red;width:150px;flex-grow:1;" >
          <span style="font:600 1.2rem/50px '宋体';color:white;text-align:center;" @click="deleteShopList()">删除</span>
        </footer>

             </div>


        </footer>
 
    </div>
</template>
<script>
import axios from "axios";
import { Dialog } from 'vant';
export default {
  components:{
       [Dialog.Component.name]: Dialog.Component,
  },
  mounted() {
    axios.get("/api/v1/shoppingcartList").then(res => {
      this.shoppingCartList = res.data.shoppingCartList;
    });
    axios.get("/api/v1/recommendGoodsList").then(res => {
      this.recommendGoodsList = res.data.recommendGoodsList;
    });
  },

  data() {
    return {
      shoppingCartList: [],
      recommendGoodsList: [],
      allSelected: false,
      isEdit: false,
      porductModel: [],

      canBuy: false,
      isOrange: true,
      isShowActionSheet:false,// 是否显示actionsheet控制开关
      actionSheetGoods:{},//在actionsheet中要显示的商品。
      newProductModel:[],//表示当前商品所有的型号列表。
      
    };
  },
  computed: {
    totalPrice: function() {
      let prices = 0;
      this.shoppingCartList
        .filter(item1 => item1.selected == true)
        .forEach(item2 => {
          prices += item2.price * item2.number;
        });

      return prices;
    },
    totalProductsNum: function() {
      let num = 0;
      this.shoppingCartList
        .filter(item1 => item1.selected == true)
        .forEach(item2 => {
          num += item2.number;
        });

      return num;
    }
  },
  methods: {
    // 从推荐列表中添加商品到购物车
    addShoppingCart(goods){
      //  1 把当前商品加入到购物车列表
      goods.selected=true;
      this.shoppingCartList.push(goods);
      // 2 把当前商品从推荐列表中删除
    //  this.recommendGoodsList.splice(this.recommendGoodsList.findIndex(item=>item.id == goods.id),1);
    // 3发送 ajax请求获取推荐列表。
       axios.get("/api/v1/recommendGoodsList")
       .then(res=>{
         this.recommendGoodsList = res.data.recommendGoodsList;

       });
    },
    // 给动作面板中的型号值添加点击事件使其被选中
    changeModelValue(goods,modelName,value){
      // 添加选中的动作
      this.newProductModel.forEach(item=>{
        if(item.modelName == modelName ){
          item.values.forEach(item2=>{
            if(item2.name == value){
              item2.state= true;
            }else{
              item2.state= false;
            }
          })
        }
      });
      // 修改商品信息
      goods.model.forEach(item=>{
        if(item.modelName==modelName){
          item.value=value;
        }
      })
    },
    //动作面板数据的获取
    showActionSheet(goods){
         this.isShowActionSheet= true;
         this.actionSheetGoods=goods;
         let productModel=[];
         //发送ajax到后台获取当前商品的所有型号
         axios.get("/api/v1/getProductModelById?goodsId="+goods.id)
         .then(res=>{
              productModel= res.data.productModel;
              // 改变型号中要突出表现的项
              productModel.forEach(model=>{
                //循环遍历goods里的模型
                 this.actionSheetGoods.model.forEach(goodsModle=>{
                   if(model.modelName == goodsModle.modelName){
                     model.values.forEach(value=>{
                       if(value.name == goodsModle.value){
                         value.state= true;
                       }else{
                         value.state= false;
                       }
                     })
                   }
                 });
              });
              this.newProductModel=productModel;
         });

    },
    deleteShopList(){
     // 找到被选中的商品index 
     // 挨个从类别中移出

      // let list=[];
      //   for(let t=0;t<this.shoppingCartList.length;t++){
      //     //找到被选中的商品
      //     if(this.shoppingCartList[t].selected){
      //       // 保存要删除商品的下标
      //       list.push(this.shoppingCartList[t]);
      //     }
      //     }
      //    // console.log("要删除的商品下标："+deletIndex);
      //   // 删除操作
      //   for(let i=0;i<list.length;i++){
      //     // console.log(i+":"+deletIndex[i]);
      //       let index = this.shoppingCartList.findIndex(item=>item.id==list[i].id);
      //       this.shoppingCartList.splice(index,1);
      //   }
       // 循环购物列表，找select为true的 删掉。
        this.shoppingCartList
        .filter((goods) => goods.selected)
        .map((goods) => {
          this.shoppingCartList.splice(
            this.shoppingCartList.findIndex((item) => {
              item.id == goods.id;
            }),
            1
          );
        });
      
    },
 
  
    changeEdit(str) {
      if ("edit" == str) {
        this.isEdit = true;
        //发送ajax请求 需要传递当前购物车列表中所有商品id。得到的数据需要赋值给data里面的porductModel
        //得到所有的商品id 拼接成字符串放到url后面
        let strId = "";
        this.shoppingCartList.forEach(item => {
          strId = strId + item.id + ",";
        });
        axios
          .get("/api/v1/AllModels?goodsId=" + strId)
          .then(res => (this.porductModel = res.data.porductModel));
      } else this.isEdit = false;
    },
    changeState() {
      let unSelectedList = this.shoppingCartList.filter(
        item => item.selected == false
      );
      if (null == unSelectedList || unSelectedList.length == 0) {
        this.allSelected = true;
      } else {
        this.allSelected = false;
      }
    },
    changeAllSelect() {
      this.shoppingCartList.map(item => (item.selected = this.allSelected));
    },
    add(goods) {
      goods.number++;
    },

    reduce(goods) {
      // 当商品数量为1的时候再减少数量相当于删除该商品
      if (goods.number > 1) {
        goods.number--;
      } else {
        //从当前商品列表里面吧该商品删除掉。
        Dialog.confirm({
            
            message: '你确定删除该商品？',
          })
            .then(() => {
              let index = this.shoppingCartList.findIndex(
            item => item.id == goods.id
          );
          this.isShowActionSheet=false;
          this.shoppingCartList.splice(index, 1);
         
            })
            .catch(() => {
              // on cancel
            });
        // if (confirm("你确定删除该商品？")) {
        //   let index = this.shoppingCartList.findIndex(
        //     item => item.id == goods.id
        //   );
        //   this.shoppingCartList.splice(index, 1);
        // }
      }
    }
  },
  watch: {
    // 侦听器

    shoppingCartList() {
      // alert(this.allSelected);
      this.$bus.$emit("totalnumChange", this.shoppingCartList.length);
    }
  }
};
</script>
<style lang="scss" scoped>
.valueselected{
  border:1px solid #ff6600;
  color:#ff6600;
  padding:10px
  
}

.model-content{
  padding-bottom:160px;
  img{
    width:100px;
    height:100px;
  }
  header{
    display:flex;
    flex-direction: row;

  }
}


.gray {
  background-color: #999 !important;
}

.no-edit {
  flex-grow: 1;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  text-align: center;
  background-color: #f0f0f0;
}

.settlement {
  position: fixed;
  bottom: 67px;
  height: 55px;
  width: 100%;
  background-color: #f0f0f0;
  display: flex;
  flex-direction: row;
  justify-content: space-around;

  .button {
    width: 140px;
    background-color: #ff6600;
    text-align: center;
    color: #fff;
    font: bold 1.5rem "宋体";
  }
}

.recommend-list {
  background-color: hsl(0, 0%, 98%);

  .title {
    text-align: center;
    padding: 20px 0 10px 0;
    height: 50px;
    img {
      width: 140px;
      height: 20px;
    }
  }
  .recommend-goods-list {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-around;
    padding-bottom: 120px;
    margin:10px;

    .recommend-item {
      width: calc(50% - 10px);
      img {
        width: 100%;
      }
    }
  }
}

.goods-list {
  min-height: 300px;
  background-color: #fafafa;
}
.normal-checkbox:checked {
  background: #1673ff;
}
.normal-checkbox {
  margin-top: 10px;
  width: 25px;
  height: 25px;
  background-color: #ffffff;
  border: solid 1px #aaaaaa;
  -webkit-border-radius: 50%;
  border-radius: 50%;
  font-size: 0.8rem;
  margin: 0;
  padding: 0;
  position: relative;
  display: inline-block;
  vertical-align: top;
  cursor: default;
  -webkit-appearance: none;
  -webkit-user-select: none;
  user-select: none;
  -webkit-transition: background-color ease 0.1s;
  transition: background-color ease 0.1s;
}
.normal-checkbox:checked::after {
  content: "";
  top: 5px;
  left: 5px;
  position: absolute;
  background: transparent;
  border: #fff solid 2px;
  border-top: none;
  border-right: none;
  height: 6px;
  width: 10px;
  -moz-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  -webkit-transform: rotate(-45deg);
  transform: rotate(-45deg);
}
.goods-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  background-color: #fff;
  margin-bottom: 10px;
  .item-img {
    width: 80px;
    height: 80px;
    border: 1px solid #ccc;
    margin: 30px 10px 30px 5px;
  }
  .item-button {
    float: right;
    margin-right: 20px;
    margin-bottom: 0px;
  }
  .normal-button {
    width: 30px;
    height: 30px;
    border: 1px solid #e0e0e0;
    margin-bottom: 0px;
  }
  .normal-input {
    width: 26px;
    height: 26px;
    text-align: center;
    border-left: 0px;
   
    border-right: 0px;
    border-top: 1px solid #e0e0e0;
    border-bottom: 1px solid #e0e0e0;
  }

  .item-detail {
    flex-grow: 1;
    max-width: 120px;
  }
}

.free {
  width: 95px;
  margin: 0 auto;
  text-align: center;
  color: #cccccc;
  font-size: 1.1rem;
  .free-img {
    width: 60px;
    height: 60px;
    margin: 50px 0 20px 0;
  }
  .button {
    padding: 10px 20px;
    border: 1px solid #cccccc;
    margin-top: 30px;
  }
}

.title {
  background-color: #fafafa;
  height: 45px;
  border-bottom: 0.5px solid #e0e0e0;
  text-align: center;
  .title-aside {
    position: absolute;
    top: 8px;
    right: 0px;
    width: 80px;
    height: 45px;
    margin-left: 0px;
    img {
      width: 30px;
      height: 20px;
    }
  }
}
</style>

